<script setup lang="tsx">
import type { DataTableCreateSummary, DataTableInst, DropdownOption } from 'naive-ui';
import { NGradientText, NTag, useDialog, useMessage } from 'naive-ui';
import { h, nextTick, onMounted, ref, watch } from 'vue';
import {
  // fetchAddDetail,
  fetchDeleteBatchOrder,
  fetchDeleteOrder,
  fetchGetAllOrder,
  fetchGetAllOrderByRunning,
  // fetchEditOrder,
  fetchPatchOrder,
  fetchPrintOrder
} from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
// import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import UserOperateDrawer from '../modules/user-operate-drawer.vue';
import UserOperateModel from '../modules/user-operate-model.vue';
import UserSearch from '../modules/user-search.vue';
import Detail from '../modules/detail.vue';
import OrderModel from '../modules/order-model.vue';

const appStore = useAppStore();
const dialog = useDialog();
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetAllOrder,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    // {
    //   key: 'index',
    //   title: $t('common.index'),
    //   align: 'center',
    //   width: 64
    // },
    {
      key: 'id',
      title: '订单ID',
      align: 'center',
      width: 68,
      resizable: true
    },
    {
      key: 'desk',
      // title: $t('page.food.order.desk'),
      title(column) {
        return h(
          NGradientText,
          {
            size: '20',
            type: 'info'
          },
          { default: () => $t('page.food.order.desk') }
        );
      },
      align: 'center',
      width: 100,
      render: row => {
        return <NTag type="info">{row.desk}</NTag>;
      }
    },
    // {
    //   key: 'title',
    //   title: $t('page.food.dish.title'),
    //   align: 'center',
    //   minWidth: 100
    // },
    {
      key: 'price',
      title: $t('page.food.order.price'),
      align: 'center',
      width: 120
    },
    {
      key: 'afterprice',
      // title: $t('page.food.order.afterprice'),
      title(column) {
        return h(
          NGradientText,
          {
            size: '20',
            type: 'warning'
          },
          { default: () => $t('page.food.order.afterprice') }
        );
      },
      align: 'center',
      defaultSortOrder: 'ascend',
      sorter: 'default',
      width: 120,
      render: row => {
        return <NTag type="error">{row.afterprice}</NTag>;
      }
    },
    {
      key: 'sale',
      title: $t('page.food.order.sale'),
      align: 'center',
      width: 120
    },
    {
      key: 'customer',
      title: $t('page.food.order.customer'),
      align: 'center',
      width: 120
    },
    {
      key: 'waiter',
      title: $t('page.food.order.waiter'),
      align: 'center',
      width: 120
    },
    {
      key: 'current',
      // title: $t('page.food.order.current'),
      title(column) {
        return h(
          NGradientText,
          {
            size: '20',
            type: 'danger'
          },
          { default: () => $t('page.food.order.current') }
        );
      },
      align: 'center',
      width: 120,
      render: row => {
        if (row.current === null) {
          return null;
        }

        return <NTag type={row.current === '进行中' ? 'warning' : 'success'}>{row.current}</NTag>;
      }
    },
    {
      key: 'description',
      title: $t('page.food.order.description'),
      align: 'center',
      width: 120
    },
    {
      key: 'message',
      title: $t('page.food.order.message'),
      align: 'center',
      width: 120
    },
    {
      key: 'times',
      title: $t('page.food.dish.times'),
      align: 'center',
      width: 200,
      render: row => {
        return row.times.split('+')[0];
      }
    }
    // {
    //   key: 'operate',
    //   title: $t('common.operate'),
    //   align: 'center',
    //   width: 130,
    //   render: row => (
    //     <div class="flex-center gap-8px">
    //       {/* <NButton type="warning" ghost size="small" onClick={() => actived('bottom', row.id)}>
    //         {$t('common.order')}
    //       </NButton> */}
    //       <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
    //         {$t('common.edit')}
    //       </NButton>
    //       {/* <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
    //         {{
    //           default: () => $t('common.confirmDelete'),
    //           trigger: () => (
    //             <NButton type="error" ghost size="small">
    //               {$t('common.delete')}
    //             </NButton>
    //           )
    //         }}
    //       </NPopconfirm> */}
    //     </div>
    //   )
    // }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

const message = useMessage();

const raw = ref<Api.Food.Count[]>();
onMounted(async () => {
  await refreshOrderRunning();
});

async function refreshOrderRunning() {
  const datas = await fetchGetAllOrderByRunning();
  if (datas.error) {
    console.log('获取order全量数据失败', datas.error);
  } else {
    console.log('datas', datas);
    const tmp = [];
    if (datas.data === null) {
      raw.value = [];
      return;
    }
    datas.data?.forEach(item => {
      tmp.push(item.id);
    });
    const shunxu = tmp.sort();
    console.log('顺序', shunxu);
    const result = [];
    shunxu.forEach(name => {
      datas.data.forEach(item => {
        if (item.id === name) {
          result.push(item);
        }
      });
    });

    raw.value = result;
    // raw.value?.sort();
    console.log('all data', raw.value);
  }
}

const dishactive = ref(false);
const formValue = ref({
  dish: null,
  orders: 0,
  number: 1,
  price: 0,
  message: ''
});
const currentSale = ref(0.0);

// const formData = ref<Api.Food.Detail>();

// const realdishactive = ref(false);
const ordertitle = ref('');
// const formattedValue = ref('2007-06-30');
const currentid = ref<any>('0');
const drawerVisibleNew = ref(false);
const drawerVisibleOld = ref(false);
const modelVisible = ref(false);
const currentSelectOrder = ref<Api.Food.Order>();
const actived = (id: string) => {
  dishactive.value = true;
  drawerVisibleNew.value = true;
  currentid.value = id;
  console.log('setcurrentid', id, currentid);
};

const activedOld = (id: string) => {
  dishactive.value = true;
  drawerVisibleOld.value = true;
  currentid.value = id;
  console.log('setcurrentid', id, currentid);
};

// 表格右鍵
const showDropdown = ref(false);
const x = ref(0);
const y = ref(0);
const dropdownoptions: DropdownOption[] = [
  {
    label: '编辑',
    key: 'edit'
  },
  {
    label: () => h('span', { style: { color: 'red' } }, '删除'),
    key: 'delete'
  }
];

function handleNegativeClick() {
  message.info('已取消');
}

function handleSelect(key: string) {
  showDropdown.value = false;

  if (key === 'edit') {
    message.warning(`当前选中桌号 ${currentSelectOrder.value.desk} 订单进行编辑`);
    editingData.value = currentSelectOrder.value;
    operateType.value = 'edit';
    drawerVisible.value = true;
  } else if (key === 'delete') {
    message.error(`当前选中桌号 ${currentSelectOrder.value.desk} 订单删除`);
    dialog.error({
      title: '删除订单',
      content: `确定要删除 【${currentSelectOrder.value.desk}】 的订单吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onNegativeClick: handleNegativeClick,
      onPositiveClick: () => {
        handleDelete(currentSelectOrder.value.id);
      }
    });
  }
}
function onClickoutside() {
  showDropdown.value = false;
}

const rowProps = (row: Api.Food.Order) => {
  return {
    style: 'cursor: pointer;',
    onClick: async () => {
      message.info(`当前选中桌号 ${row.desk} 进行点菜`);
      ordertitle.value = `桌号 ${row.desk} - 折扣 【${row.sale}】 - 顾客 【${row.customer}】- 状态 【${row.current}】- 开始时间 【${row.times}】`;
      actived(row.id);
      currentid.value = row.id;
      formValue.value.orders = row.id;
      currentSale.value = row.sale;
      currentSelectOrder.value = row;
      // console.log('setcurrentid2', currentid);
      // refreshDetail();
      // closeDrawer();
    },
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      currentSelectOrder.value = row;
      e.preventDefault();
      showDropdown.value = false;
      nextTick().then(() => {
        showDropdown.value = true;
        x.value = e.clientX;
        y.value = e.clientY;
      });
    }
  };
};

async function handleBatchDelete() {
  // request
  const { error, data } = await fetchDeleteBatchOrder(checkedRowKeys.value);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    // console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  // console.log(checkedRowKeys.value);

  onBatchDeleted();
}

async function handleDelete(id: number) {
  // request
  const { error, data } = await fetchDeleteOrder(id);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    // console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  // console.log(id);

  onDeleted();
}

function handleEditNew(row: Api.Food.Count) {
  // console.log('neweeee', row, data);
  // 去原始数据里面找
  data.value.forEach(item => {
    // console.log('item', item);
    if (item.desk === row.desk) {
      // console.log('got it', item, row);
      currentSelectOrder.value = item;
      editingData.value = item;

      operateType.value = 'edit';
      // drawerVisible.value = true;
      modelVisible.value = true;
    }
  });
  message.warning(`当前选中桌号 ${row.desk} 订单进行编辑`);
}

// function edit(id: number) {
//   handleEdit(id);
// }

// function handleAddDetail() {
//   realdishactive.value = true;
// }

const closedd = () => {
  // dishactive.value = false;
  drawerVisibleNew.value = false;
  refreshOrderRunning();
};

function handleAddNew() {
  operateType.value = 'add';
  editingData.value = null;
  // drawerVisible.value = true;
  modelVisible.value = true;
}

const handleOrder = (row: Api.Food.Count) => {
  message.info(`当前选中桌号 ${row.desk} 进行点菜`);
  ordertitle.value = `桌号 ${row.desk} - 折扣 【${row.sale}】 - 顾客 【${row.customer}】- 状态 【${row.current}】- 开始时间 【${row.times}】`;
  activedOld(row.id);
  currentid.value = row.id;
  formValue.value.orders = row.id;
  currentSale.value = row.sale;
  currentSelectOrder.value = row;
};

const createSummary: DataTableCreateSummary = pageData => {
  return {
    name: {
      value: h(
        'span',
        { style: { color: 'red' } },
        (pageData as RowData[]).reduce((prevValue, row) => prevValue + row.afterprice, 0)
      ),
      colSpan: 3
    }
  };
};

const tableOrderRef = ref<DataTableInst>();
const downloadCsv = () => {
  tableOrderRef.value?.downloadCsv({ fileName: 'Sheet1' });
};

const showSuffix = ref(true);

async function handleSubmitOrder(row: any) {
  // console.log('item', item);
  // console.log('got it', item, row);
  console.log('tmp', row);
  const tmp = {
    price: 0,
    afterprice: 0,
    current: '进行中',
    id: 0
  };
  const basic = row.count?.基础消费 === undefined ? 0 : row.count?.基础消费;
  const wine = row.count?.酒水饮料 === undefined ? 0 : row.count?.酒水饮料;
  const food = row.count?.菜品消费 === undefined ? 0 : row.count?.菜品消费;
  const beforefood = row.count?.菜品消费未打折 === undefined ? 0 : row.count?.菜品消费未打折;
  console.log('basic', basic, 'wine', wine, 'food', food, 'before', beforefood, 'roqw', row);
  tmp.afterprice = basic + wine + food;
  tmp.price = basic + wine + beforefood;
  tmp.current = '已结账';
  tmp.id = Number.parseInt(row.id, 10);
  console.log('tmp2', row);

  const datas = await fetchPatchOrder(row.id, tmp);
  if (datas.error) {
    message.error(datas.error.message);
  } else {
    row.current = '已结账';
    // dishactive.value = false;
    message.success(`结账成功 ${datas.data}`);
    // refreshOrderRunning();
  }
  // message.success(`结账成功`);
  message.warning(`当前选中桌号 ${row.desk} 订单进行编辑`);
}

async function handleSubmitPrintOrder(row: any) {
  // console.log('item', item);
  // console.log('got it', item, row);
  console.log('tmp', row);
  const tmp = {
    price: 0,
    afterprice: 0,
    current: '进行中',
    id: 0
  };
  const basic = row.count?.基础消费 === undefined ? 0 : row.count?.基础消费;
  const wine = row.count?.酒水饮料 === undefined ? 0 : row.count?.酒水饮料;
  const food = row.count?.菜品消费 === undefined ? 0 : row.count?.菜品消费;
  const beforefood = row.count?.菜品消费未打折 === undefined ? 0 : row.count?.菜品消费未打折;
  console.log('basic', basic, 'wine', wine, 'food', food, 'before', beforefood, 'roqw', row);
  tmp.afterprice = basic + wine + food;
  tmp.price = basic + wine + beforefood;
  tmp.current = '已结账';
  tmp.id = Number.parseInt(row.id, 10);

  const datas = await fetchPrintOrder(row.id, tmp);
  if (datas.error) {
    message.error(datas.error.message);
  } else {
    message.success('打印成功');
  }
}

watch(data, async () => {
  await refreshOrderRunning();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px lt-sm:overflow-auto">
    <NCard :title="$t('route.food_order_menu')" :bordered="false" size="small" class="card-wrapper">
      <NTabs type="line" default-value="cards" justify-content="space-evenly" animated>
        <NTabPane name="cards" size="large" tab="收银">
          <NGrid cols="5 s:3 m:3 l:4 xl:4 2xl:4" responsive="screen">
            <NGi class="adds">
              <NCard>
                <NResult
                  status="418"
                  size="huge"
                  title="新增订单"
                  description="点击任意位置添加"
                  @click="handleAddNew"
                ></NResult>
                <template #action>
                  <NFlex justify="space-around" size="large" vertical>
                    <NButton type="primary" size="large" @click="refreshOrderRunning">刷新</NButton>
                  </NFlex>
                </template>
              </NCard>
            </NGi>
            <NGi v-for="(info, i) in raw" :key="i" :class="info.current === '进行中' ? 'green' : 'light-green'">
              <NCard
                :title="info.desk"
                :header-style="
                  info.current === '进行中' ? 'background-color: #f0f9eb' : 'background-color: rgb(255 112 138);'
                "
              >
                <template #header-extra>
                  <NTag :type="info.current === '进行中' ? 'warning' : 'success'" @click="handleOrder(info)">
                    {{ info.current }}
                  </NTag>
                </template>
                <NSpace vertical @click="handleOrder(info)">
                  <NSpace :size="12">
                    <NStatistic label="菜品消费" tabular-nums>
                      <template #prefix>¥</template>
                      {{ info.count.菜品消费 === undefined ? 0 : info.count.菜品消费?.toFixed(1) }}
                    </NStatistic>
                    <NStatistic label="基础消费" tabular-nums>
                      <template #prefix>¥</template>
                      {{ info.count?.基础消费 === undefined ? 0 : info.count?.基础消费 }}
                    </NStatistic>
                    <NStatistic label="酒水饮料" tabular-nums>
                      <template #prefix>¥</template>
                      {{ info.count?.酒水饮料 === undefined ? 0 : info.count?.酒水饮料 }}
                    </NStatistic>
                    <NStatistic label="点菜数" tabular-nums>
                      {{ info.count?.number }}
                    </NStatistic>
                    <NStatistic label="折扣" tabular-nums>
                      <span style="color: red">{{ info.tsale }}</span>
                    </NStatistic>
                    <NStatistic label="原价" tabular-nums>
                      <template #prefix>¥</template>
                      {{ (info.count?.酒水饮料 + info.count?.基础消费 + info.count?.菜品消费未打折).toFixed(1) }}
                    </NStatistic>
                    <NStatistic label="折后价" tabular-nums>
                      <template #prefix>¥</template>
                      <span style="color: red">
                        {{ (info.count?.酒水饮料 + info.count?.基础消费 + info.count?.菜品消费).toFixed(1) }}
                      </span>
                    </NStatistic>

                    <NDivider dashed></NDivider>
                    <NStatistic label="订餐时间" tabular-nums>
                      <template #prefix></template>
                      {{ info.times.split('+')[0].replace('T', '') }}
                    </NStatistic>
                  </NSpace>
                </NSpace>
                <template #footer>
                  <NFlex justify="space-between" size="large">
                    <NButton type="primary" tertiary size="large" @click="handleOrder(info)">点餐</NButton>
                    <NPopconfirm @positive-click="handleSubmitPrintOrder(info)" @negative-click="handleNegativeClick">
                      <template #trigger>
                        <NButton size="large" tertiary type="info">打印</NButton>
                      </template>
                      是否打印当前订单？
                    </NPopconfirm>
                    <NButton type="warning" tertiary size="large" @click="handleEditNew(info)">编辑</NButton>
                    <NPopconfirm @positive-click="handleDelete(info.id)" @negative-click="handleNegativeClick">
                      <template #trigger>
                        <NButton size="large" tertiary type="error">删除</NButton>
                      </template>
                      是否删除当前订单？
                    </NPopconfirm>
                  </NFlex>
                </template>
                <template #action>
                  <NFlex vertical size="large">
                    <NPopconfirm @positive-click="handleSubmitOrder(info)" @negative-click="handleNegativeClick">
                      <template #trigger>
                        <NButton size="large" type="success">结账</NButton>
                      </template>
                      是否删除当前订单？
                    </NPopconfirm>
                  </NFlex>
                </template>
              </NCard>
            </NGi>
            <NGi v-if="showSuffix" suffix class="suffix" #="{ overflow }">
              {{ overflow ? '存在溢出' : '' }}
              <NPopover trigger="hover">
                <template #trigger>
                  <NFlex justify="space-around" size="large">
                    <NQrCode value="https://www.lflxp.top" :size="100" />
                    <NDivider dashed>上面是在线收银 下面是小程序</NDivider>
                    <NQrCode value="https://h5.lflxp.top/wechat/login" :size="100" />
                    <!--
 <NDivider dashed>下面是小程序直接登录</NDivider>
                    <NQrCode value="https://h5.lflxp.top/wechat/login/jump" :size="100" />
                    <NDivider dashed>下面是小程序测试</NDivider>
                    <NQrCode value="https://h5.lflxp.top/wechat/test" :size="100" /> 
-->
                  </NFlex>
                </template>
                扫描访问在线订单平台
              </NPopover>
            </NGi>
          </NGrid>
        </NTabPane>
        <NTabPane name="table" tab="详情">
          <NCard class="card-wrapper">
            <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
            <template #footer>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                kind="order"
                @add="handleAdd"
                @delete="handleBatchDelete"
                @refresh="getData"
                @download="downloadCsv"
              />
              <NDataTable
                ref="tableOrderRef"
                v-model:checked-row-keys="checkedRowKeys"
                striped
                :columns="columns"
                :data="data"
                size="large"
                :flex-height="!appStore.isMobile"
                :scroll-x="962"
                :loading="loading"
                remote
                :row-key="row => row.id"
                :pagination="mobilePagination"
                :row-props="rowProps"
                :summary="createSummary"
                :style="{ height: appStore.isMobile ? 'auto' : '600px' }"
                class="sm:h-full"
              />
            </template>
          </NCard>
        </NTabPane>
      </NTabs>

      <NDropdown
        placement="bottom-start"
        trigger="manual"
        :x="x"
        :y="y"
        :options="dropdownoptions"
        :show="showDropdown"
        :on-clickoutside="onClickoutside"
        @select="handleSelect"
      />
      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />

      <UserOperateModel
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
      <!--
 <DishOperateDrawer
        v-model:visible="dishactive"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      /> 
-->

      <Detail
        v-model:visible="drawerVisibleNew"
        v-model:loading="loading"
        :ordertitle="ordertitle"
        :order="currentSelectOrder"
        :currentid="currentid"
        :current-sale="currentSale"
        @closedd="closedd"
        @on-deleted="onDeleted"
      />

      <OrderModel
        v-model:visible="drawerVisibleOld"
        v-model:loading="loading"
        :ordertitle="ordertitle"
        :order="currentSelectOrder"
        :currentid="currentid"
        :current-sale="currentSale"
        @closedd="closedd"
        @on-deleted="onDeleted"
      />
    </NCard>
  </div>
</template>

<style scoped>
.card-tabs .n-tabs-nav--bar-type {
  padding-left: 4px;
}

.adds {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.light-green {
  /* height: 100%; */
  padding: 10px;
  /* background-color: rgba(0, 128, 0, 0.12); */
  display: flex;
  align-items: center;
  justify-content: center;
}
.green {
  /* height: 300px; */
  padding: 10px;
  /* background-color: #df7e40; */
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
